package com.lgcns.andteam2.todaymenu;

import java.util.HashMap;

import android.app.TimePickerDialog;
import android.app.TimePickerDialog.OnTimeSetListener;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.CheckBoxPreference;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.PreferenceScreen;
import android.preference.Preference.OnPreferenceChangeListener;
import android.preference.PreferenceActivity;
import android.preference.PreferenceManager;
import android.text.TextUtils;
import android.text.format.DateFormat;
import android.util.Log;
import android.widget.TimePicker;

import com.lgcns.andteam2.todaymenu.db.QueryHelper;
import com.lgcns.andteam2.todaymenu.info.PlaceInfo;

/**
 * 설정화면에 대한 activity
 */
public class SettingActivity extends PreferenceActivity implements OnPreferenceChangeListener, OnTimeSetListener {
    private static final String TAG = SettingActivity.class.getSimpleName();
    
    private CheckBoxPreference mLunchAlarmEnabledPref;
    private Preference mLunchTimePref;
    private CheckBoxPreference mDinnerAlarmEnabledPref;
    private Preference mDinnerTimePref;
    private int mTimePickerType = -1;
    
    private ListPreference mPlacePref;
    private SharedPreferences mSharedPref;
    private PlaceInfo mMyPlace; 
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        mSharedPref = PreferenceManager.getDefaultSharedPreferences(this);

        // 사업장 목록을 가져온다.
        HashMap<String, String[]> map = QueryHelper.getPlaceList(this);
        String[] placeId = map.get("placeId");
        String[] place = map.get("place");
        
        // 설정값이 없는 경우 기본값은 맨 처음 조회되는 사업장을 기본으로 설정함.
        mMyPlace = PlaceInfo.getInstance(this);
        
        // 미리 알림 설정값이 없는 경우 기본 값 지정
        String lunchAlarmTime = mSharedPref.getString(Constants.PREF_LUNCH_ALARM_TIME, null);
        Log.d(TAG, "Preference - lunchAlarmTime : " + lunchAlarmTime);
        if(TextUtils.isEmpty(lunchAlarmTime)) {
            Util.savePreference(this, Constants.PREF_LUNCH_ALARM_TIME, Constants.PREF_DEFAULT_LUNCH_ALARM_TIME);
        }
        String dinnerAlarmTime = mSharedPref.getString(Constants.PREF_DINNER_ALARM_TIME, null);
        Log.d(TAG, "Preference - dinnerAlarmTime : " + dinnerAlarmTime);
        if(TextUtils.isEmpty(dinnerAlarmTime)) {
            Util.savePreference(this, Constants.PREF_DINNER_ALARM_TIME, Constants.PREF_DEFAULT_DINNER_ALARM_TIME);
        }

        addPreferencesFromResource(R.xml.setting);

        mPlacePref = (ListPreference)findPreference(Constants.PREF_PLACE_ID);
        mPlacePref.setEntryValues(placeId);
        mPlacePref.setEntries(place);
        mPlacePref.setOnPreferenceChangeListener(this);
        
        mLunchAlarmEnabledPref = (CheckBoxPreference)findPreference(Constants.PREF_LUNCH_ALARM_ENABLED);
        mLunchAlarmEnabledPref.setOnPreferenceChangeListener(this);
        mLunchTimePref = (Preference)findPreference(Constants.PREF_LUNCH_ALARM_TIME);
        
        mDinnerAlarmEnabledPref = (CheckBoxPreference)findPreference(Constants.PREF_DINNER_ALARM_ENABLED);
        mDinnerAlarmEnabledPref.setOnPreferenceChangeListener(this);
        mDinnerTimePref = (Preference)findPreference(Constants.PREF_DINNER_ALARM_TIME);
    }
    
    @Override
    protected void onResume() {
        super.onResume();
        
        mPlacePref.setSummary(mPlacePref.getEntry());
        setLunchTimeSummary();
        setDinnerTimeSummary();
    }
    
    /**
     * 점심 알람 시간 summery를 설정한다.
     */
    private void setLunchTimeSummary() {
        String lunchAlarmTime = mSharedPref.getString(Constants.PREF_LUNCH_ALARM_TIME, null);
        mLunchTimePref.setSummary(Util.formatDatePref(this, (String)lunchAlarmTime));
    }
    
    /**
     * 저녁 알람 시간 summery를 설정한다.
     */
    private void setDinnerTimeSummary() {
        String dinnerAlarmTime = mSharedPref.getString(Constants.PREF_DINNER_ALARM_TIME, null);
        mDinnerTimePref.setSummary(Util.formatDatePref(this, (String)dinnerAlarmTime));
    }
    
    @Override
    public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen, Preference preference) {
        if(preference == mLunchTimePref) {
            showTimePicker(Constants.PREF_LUNCH_ALARM_TIME);
            mTimePickerType = Constants.LUNCH_ALARM_DIALOG;
        } else if(preference == mDinnerTimePref) {
            mTimePickerType = Constants.DINNER_ALARM_DIALOG;
            showTimePicker(Constants.PREF_DINNER_ALARM_TIME);
        }
        
        return super.onPreferenceTreeClick(preferenceScreen, preference);
    }
    
    /**
     * 날짜 입력 Dialog를 표시한다.
     * @param key
     */
    private void showTimePicker(String key) {
        String alarmTime = mSharedPref.getString(key, null);
        String[] time = alarmTime.split(":");
        int hourOfDay = Integer.parseInt(time[0]);
        int minute = Integer.parseInt(time[1]);
        
        TimePickerDialog dialog = new TimePickerDialog(this, this, hourOfDay, minute, DateFormat.is24HourFormat(this));
        dialog.setTitle(getString(R.string.pref_menu_alarm_time_dialog));
        dialog.show();
    }

    @Override
    public boolean onPreferenceChange(Preference preference, Object newValue) {
        if(preference.getKey().equals(Constants.PREF_PLACE_ID)) {
            ListPreference placePref = (ListPreference)preference;
            int index = placePref.findIndexOfValue((String)newValue);
            placePref.setSummary(placePref.getEntries()[index]);
            mMyPlace.setPlaceInfo((String)newValue, (String)placePref.getEntries()[index]);
            return true;
        } else if(preference.getKey().equals(Constants.PREF_LUNCH_ALARM_ENABLED) || preference.getKey().equals(Constants.PREF_DINNER_ALARM_ENABLED)) {
            sendBroadcast(new Intent(Constants.ACTION_ALARM_SETTING_CHANGED));
            return true;
        }
        
        return false;
    }

    @Override
    public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
        String time = hourOfDay + ":" + minute;
        Log.d(TAG, "time set : " + time);
        if(mTimePickerType == Constants.LUNCH_ALARM_DIALOG) {
            Util.savePreference(this, Constants.PREF_LUNCH_ALARM_TIME, time);
            mLunchTimePref.setSummary(Util.formatDatePref(this, time));
        } else if(mTimePickerType == Constants.DINNER_ALARM_DIALOG) {
            Util.savePreference(this, Constants.PREF_DINNER_ALARM_TIME, time);
            mDinnerTimePref.setSummary(Util.formatDatePref(this, time));
        }
        sendBroadcast(new Intent(Constants.ACTION_ALARM_SETTING_CHANGED));
    }
}
